package com.xy_pro.xymanager.auth.security;

import com.xy_pro.xymanager.entity.XYMessage;
import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import java.security.Key;
import java.util.Date;

@Component
@RequiredArgsConstructor
public class JwtTokenProvider {

    @Value("${jwt.secret}")
    private String jwtSecret;

    @Value("${jwt.expiration.ms}")
    private int jwtExpirationMs;

    private Key getSigningKey() {
        byte[] keyBytes = jwtSecret.getBytes();
        return Keys.hmacShaKeyFor(keyBytes);
    }

    public String generateJwtToken(Authentication authentication) {
        UserDetailsImpl userPrincipal = (UserDetailsImpl) authentication.getPrincipal();

        return Jwts.builder()
                .setSubject((userPrincipal.getUsername()))
                .setIssuedAt(new Date())
                .setExpiration(new Date((new Date()).getTime() + jwtExpirationMs))
                .signWith(getSigningKey(), SignatureAlgorithm.HS256)
                .compact();
    }

    public String getUserNameFromJwtToken(String token) {
        return Jwts.parser()
                .setSigningKey(getSigningKey())
                .build()
                .parseClaimsJws(token)
                .getBody()
                .getSubject();
    }

    public XYMessage validateJwtToken(String authToken) {
        XYMessage xyMessage = new XYMessage();
        xyMessage.setCode(-1);
        try {
            Jwts.parser().setSigningKey(getSigningKey()).build().parse(authToken);
            xyMessage.setCode(0);
            return xyMessage;
        } catch (MalformedJwtException e) {
            e.printStackTrace();
            xyMessage.setCode(HttpServletResponse.SC_UNAUTHORIZED);
            xyMessage.setMessage("Invalid JWT token");
        } catch (ExpiredJwtException e) {
            xyMessage.setCode(HttpServletResponse.SC_UNAUTHORIZED);
            xyMessage.setMessage("JWT token is expired");
            e.printStackTrace();
        } catch (UnsupportedJwtException e) {
            xyMessage.setCode(HttpServletResponse.SC_UNAUTHORIZED);
            xyMessage.setMessage("JWT token is unsupported");
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            xyMessage.setCode(HttpServletResponse.SC_UNAUTHORIZED);
            xyMessage.setMessage("JWT claims string is empty");
            e.printStackTrace();
        } catch (Exception e) {
            xyMessage.setCode(HttpServletResponse.SC_UNAUTHORIZED);
            xyMessage.setMessage("JWT token is invalid");
            e.printStackTrace();
        }
        return xyMessage;
    }
}